import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: [
		{
			path: "/",
			redirect: "/home",
			component: () => {},
		},
		{
			path: "/home",
			name: "home",
			component: HomeView,
			meta: {
				keepAlive: true, //设置页面是否需要使用缓存
			},
		},
		{
			path: "/login",
			name: "login",
			component: () => import("../views/login.vue"),
		},
		{
			path: "/info",
			name: "info",
			component: () => import("../views/info.vue"),
		},
		{
			path: "/about",
			name: "about",
			// route level code-splitting
			// this generates a separate chunk (About.[hash].js) for this route
			// which is lazy-loaded when the route is visited.
			component: () => import("../views/AboutView.vue"),
		},
	],
});
//挂在路由导航卫士
router.beforeEach((to, form, next) => {
	//console.log(to)
	// form 从哪里来; to 到哪里去; next() 一个函数 next()放行, next('/home)强制跳转
	if (to.path === "/login") {
		return next();
	}
	//验证token
	const tokenstr = window.sessionStorage.getItem("token");
	//const tokenstr = localStorage.getItem('token')
	if (!tokenstr) {
		return next("/login");
	}
	next();
});
export default router;
